import axios from './axios'
import {ElMessage} from 'element-plus'
import router from '@/router/index';
import {removeToken} from '@/utils/auth'

export function handleRegexpTxt(item, txt, val) {
    return item.replace(txt, val);
}

export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {...params}).then(res => {
            response.call(this, res, resolve);
        }).catch(error => {
            responseError.call(this, error, reject);
        });
    });
}

export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(res => {
            response.call(this, res, resolve);
        }).catch(error => {
            responseError.call(this, error, reject);
        })
    })
}

export function postFile(url, file) {
    return new Promise((resolve, reject) => {
        let formData = new FormData();
        formData.append('file', file);
        axios.post(url, formData, {
            headers: {'Content-Type': 'multipart/form-data'}
        }).then(res => {
            response.call(this, res, resolve);
        }).catch(error => {
            responseError.call(this, error, reject);
        })
    })
}

export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params).then(res => {
            response.call(this, res, resolve);
        }).catch(error => {
            responseError.call(this, error, reject);
        })
    })
}

export function del(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, params).then(res => {
            response.call(this, res, resolve);
        }).catch(error => {
            responseError.call(this, error, reject);
        })
    })
}


const response = function (res, resolve) {
    if (res && res !== "undefined") {
        resolve(res.data);
    }
}

const responseError = function (error, reject) {
    if (error.response) {
        if (error.response.data && error.response.status) {
            let errorMsg = error.response.data.message;
            let errorCode = error.response.status;
            resCodeFun(errorCode, errorMsg);
        }
    } else {
        errorMsgTips("连接服务器失败", "error");
    }
    reject(error);
}

const resCodeFun = function (errorCode, errorMsg) {
    if (errorCode === 401) {
        //清除token
        removeToken();
        router.push({path: "/login"}).catch(e => {
            console.log(e);
        })
        errorMsgTips(errorMsg, "warning")
    } else if (errorCode === 403) {
        router.push({path: "/error/403"}).catch(e => {
            console.log(e);
        })
    } else {
        errorMsgTips(errorMsg, "warning")  
    }
}

const errorMsgTips = function (errorMsg, type) {
    ElMessage({
        showClose: true,
        message: errorMsg,
        type: type,
        duration: 3000
    })
}

